package com.zzuli.ylsystem.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzuli.ylsystem.dao.*;
import com.zzuli.ylsystem.entity.*;
import com.zzuli.ylsystem.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserController {

    @Value("${ylsystem.path.upload}")
    private String uploadPath;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MedicalimgsDao medicalimgsDao;

    @Autowired
    private SickdaysDao sickdaysDao;

    @Autowired
    private BartiDao bartiDao;

    @Autowired
    private LinkcontentDao linkcontentDao;

    @Autowired
    private FabuDao fabuDao;

    @ApiOperation(value = "上传用户信息")
    @PostMapping("/sendUserInfo")
    public Result sendUserInfo(@RequestBody User user) {
        User uu = userDao.selectUserByUnionId(user.getUnionid());
        user.setId(uu.getId());
        user.setRole(2);
        userDao.updateByPrimaryKey(user);
        return Result.ok();
    }

    @ApiOperation(value = "用户登录")
    @PostMapping("/userLogin")
    public Result userLogin(@RequestBody User user) throws IOException {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxd7800e4ca0b9dfe2&secret=d3daa3568e5964a108d8936fa97574ee&js_code="+user.getUnionid()+"&grant_type=authorization_code";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();

        if (response.isSuccessful()){
            String s = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(s);
            String unionid = jsonObject.getString("openid");
            user.setUnionid(unionid);

            User isIn = userDao.selectUserByUnionId(unionid);
            if (isIn==null){
                userDao.insert(user);
            }
            return Result.ok(unionid);
        }else {
            return Result.fail();
        }
    }

//    @ApiOperation(value = "上传图片文件")
//    @PostMapping("/sendInfoImage")
//    public Msg fileUpload(@RequestParam("file") MultipartFile multipartFile) {
//        Msg msg = new Msg();
//        FileUtil fu = new FileUtil();
//        // 获取图片的名字, 使用UUID重命名文件
//        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + fu.getSuffix(multipartFile.getOriginalFilename());
//        if (!multipartFile.isEmpty()) {
//            String savePath = uploadPath;
//            try {
//                FileUtil.uploadFile(multipartFile.getBytes(), savePath, fileName);
//                String path = "http://127.0.0.1:8080/api/worker/Info/" + fileName;
//                System.out.println(path);
//                msg.setCode(0);
//                msg.setMsg("success");
//                msg.add("src", path);
//                msg.add("title", fileName);
//                return msg;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        msg.setCode(1);
//        return msg;
//    }

    @ApiOperation(value = "上传图片文件")
    @PostMapping("/sendInfoImage")
    public JSONObject fileUpload(@RequestParam("file") MultipartFile multipartFile) {
        FileUtil fu = new FileUtil();
        // 获取图片的名字, 使用UUID重命名文件
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + fu.getSuffix(multipartFile.getOriginalFilename());
        if (!multipartFile.isEmpty()) {
            String savePath = uploadPath;
            try {
                FileUtil.uploadFile(multipartFile.getBytes(), savePath, fileName);
                String path = "http://127.0.0.1:8080/api/user/Info/" + fileName;
                Map<String, Object> map = new HashMap<>();
                map.put("src",path);
                JSONObject jsonObj = new JSONObject(map);
                return jsonObj;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @ApiOperation(value = "上传图片链接到数据库中")
    @PostMapping("/sendLinkInMysql/{unionid}")
    public Msg sendLinkInMysql(@RequestBody Medicalimgs medicalimgs,
                               @PathVariable String unionid) {
        Msg msg = new Msg();
        User user = userDao.selectUserByUnionId(unionid);
        medicalimgs.setUser(user.getId());

        String time = medicalimgsDao.findMedTime(medicalimgs.getTime());

        if (time==null){
            medicalimgsDao.insert(medicalimgs);
            msg.setCode(0);
            msg.setMsg("添加成功！！");
        }else {
            medicalimgsDao.updateByUserId(medicalimgs);
            msg.setCode(0);
            msg.setMsg("修改成功！！");
        }
        return msg;
    }

    @RequestMapping(path = "/Info/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 服务器存放路径
        fileName = uploadPath + "/" + fileName;
        // 文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("失败！！");
        }
    }

    @ApiOperation(value = "根据unionid查找用户所有的检查图片;按照时间排列")
    @GetMapping("/findUserImg")
    public Result findUserImg(@RequestParam String unionid) {
        User user = userDao.selectUserByUnionId(unionid);
        List<String> timeList = medicalimgsDao.findTimesByUserId(user.getId());
        return Result.ok(timeList);
    }

    @ApiOperation(value = "根据时间查找当天所有的检查图片")
    @GetMapping("/findUserImgByOneTime")
    public Result findUserImgByOneTime(@RequestParam(value = "unionid") String unionid,
                                       @RequestParam(value = "time") String time) {
        User user = userDao.selectUserByUnionId(unionid);
        Medicalimgs medicalimgs = medicalimgsDao.selectUserImgByOneTime(user.getId(),time);
        return Result.ok(medicalimgs);
    }

    @ApiOperation(value = "查询所有用户")
    @GetMapping("/allUser")
    public Result allUser() {
        List<User> list = userDao.selectAll();
        return Result.ok(list);
    }

    @ApiOperation(value = "添加用户确诊日期")
    @PostMapping("/insertUserSickDay")
    public Result insertUserSickDay(@RequestParam(value = "unionid") String unionid,
                                    @RequestParam(value = "time") String time) {
        User user = userDao.selectUserByUnionId(unionid);
        Sickdays sickdays = new Sickdays();
        sickdays.setDays(0);
        sickdays.setTime(time);
        sickdays.setUser(user.getId());
        sickdaysDao.insert(sickdays);
        return Result.ok();
    }

    @ApiOperation(value = "查询用户确诊天数")
    @GetMapping("/selectUserSickDay")
    public Result selectUserSickDay(@RequestParam(value = "unionid") String unionid) {
        User user = userDao.selectUserByUnionId(unionid);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        String nowTime = format.format(new Date());
        String preTime = sickdaysDao.selectSickTimeByUser(user.getId());
        int daySub = getDaySub(nowTime, preTime);
        sickdaysDao.updateUserSickDays(user.getId(),daySub);
        Integer days = sickdaysDao.selectSickByUser(user.getId());

        int i = new Random().nextInt(3);
        if (i==0){
            i++;
        }
        Barti barti = bartiDao.selectByPrimaryKey(i);

        Map<String, Object> map = new HashMap<>();
        map.put("days",days);
        map.put("article",barti);
        return Result.ok(map);
    }

    @ApiOperation(value = "查询用户是否输入确诊天数")
    @GetMapping("/selectHaveUserSick")
    public Result selectHaveUserSick(@RequestParam String unionid) {
        User user = userDao.selectUserByUnionId(unionid);
        int count = sickdaysDao.selectAll(user.getId());
        return Result.ok(count);
    }

    public static int getDaySub(String nowTime,String preTime){
        // 定义项目进行天数
        int Days = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            long time = sdf.parse(nowTime).getTime();
            long time1 = sdf.parse(preTime).getTime();
            Days = (int) ((time -time1) /(24 * 60 * 60 * 1000));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Days;
    }

    @ApiOperation(value = "获取链接内容")
    @GetMapping("/getLinkContent/{id}")
    public Result selectHaveUserSick(@PathVariable Integer id) {
        Linkcontent linkcontent = linkcontentDao.selectByPrimaryKey(id);
        return Result.ok(linkcontent);
    }

    @ApiOperation(value = "获取发布内容")
    @GetMapping("/getFaBu/{id}")
    public Result selectFaBu(@PathVariable Integer id) {
        Fabu fabu = fabuDao.selectByPrimaryKey(id);
        return Result.ok(fabu);
    }

    @ApiOperation(value = "收藏")
    @GetMapping("/shouCang/{id}")
    public Result shouCang(@PathVariable Integer id) {
        linkcontentDao.updateById(id);
        return Result.ok();
    }

    @ApiOperation(value = "查看所有收藏")
    @GetMapping("/allShouCang")
    public Result shouCang() {
        List<Linkcontent> list = linkcontentDao.allShouCang();
        return Result.ok(list);
    }
}
